<template>
  <div class="drag" ref="dragDiv">
    <div class="drag-text">{{ msg }}</div>
    <!-- 滑块分别做滑动起点、滑动中、滑动结束做事件监听 -->
    <div
      class="block block_bg"
      :class="{ block_ok_bg: is_success }"
      @touchstart="touchstart($event)"
      @touchmove="touchmove($event)"
      @touchend="touchend($event)"
      ref="moveDiv"
    ></div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
export default {
  name: "Drag",
  setup(props, contents) {
    let msg = ref("请滑动解锁");
    let is_success = ref(false);
    let moveDiv = ref(null);
    let dragDiv = ref(null);
    let maxWidth = "";
    let XStart = 0;
    //最大宽度
    onMounted(() => {
      //在组件加载完成之后获取最大滑动的宽度
      maxWidth = dragDiv.value.clientWidth - moveDiv.value.clientWidth;
      console.log(maxWidth);
    });
    function touchstart(e) {
      e.preventDefault();
      if (!is_success.value) {
        // 单指操作（e.touches获取触点数）
        // 获取触摸点坐标
        XStart = e.touches[0].clientX;
      }
    }
    function touchmove(e) {
      e.preventDefault();
      if (!is_success.value) {
        // 单指操作（e.touches获取触点数）
        // 获取触摸点坐标
        let XMove = e.changedTouches[0].clientX;
        // 如果滑动距离减上滑动的起点大于最大滑动距离，则不再滑动
        if (XMove - XStart < maxWidth) {
          // 时刻记录滑动的坐标（距离）
          moveDiv.value.style.left = XMove - XStart + "px";
        } else {
          // 滑动到最大距离
          moveDiv.value.style.left = maxWidth + "px";
        }
      }
    }
    function touchend(event) {
      event.preventDefault;
      if (!is_success.value) {
        //终点坐标减上起点坐标小于最大距离即为成功
        if (event.changedTouches[0].clientX - XStart < maxWidth) {
          // 滑动失败,滑块回到初始位置
          moveDiv.value.style.left = "0px";
        } else {
          //将滑块内文字改变
          msg.value = "解锁成功";
          // 将is_success设置为true及加上成功的类名（样式）
          is_success.value = true;
          //调用外层方法
          contents.emit("unlock");
        }
      }
    }
    return {
      msg,
      is_success,
      moveDiv,
      dragDiv,
      touchend,
      touchmove,
      touchstart,
    };
  },
};
</script>

<style lang="scss" scoped>
.drag {
  position: relative;
  background-color: rgb(185, 166, 205);
  width: 100%;
  height: 45px;
  line-height: 45px;
  text-align: center;
  border-radius: 5px;

  .drag-text {
  }
  .block {
    width: 60px;
    height: 45px;
    border-radius: 5px;
    cursor: move;
    position: absolute;
    top: 0;
    left: 0;
  }
  .block_bg {
    background: gray url(../assets/imge/you.jpeg) no-repeat center;
    background-size: 20px 20px;
  }
  .block_ok_bg {
    background: gray url(../assets/imge/gg.webp) no-repeat center;
    background-size: 20px 20px;
  }
}
</style>
